//
//  YAYIEditTagGroupViewController.m
//  yayi-医生版
//
//  Created by Veer on 16/4/28.
//  Copyright © 2016年 Veer. All rights reserved.
//

#import "YAYIEditTagGroupViewController.h"
#import "YAYIEditTagGroupCollectionCell.h"


#import "YAYIMyPatientItem.h"

@interface YAYIEditTagGroupViewController () <UICollectionViewDelegate, UICollectionViewDataSource, YAYIAddMemberViewControllerDelegate>

@property (nonatomic, weak) UIView *headView;
@property (nonatomic, weak) UITextField *groupNameTf;

@property (nonatomic, weak) UICollectionView *collectionView;
@property (nonatomic, weak) UIView *bottomLineView;

// 模拟网络数据
@property (nonatomic, strong) NSArray  *serverDataArr;//数据源

@property (nonatomic, strong) NSMutableArray *patientArray;

// 当前类型
@property (nonatomic, assign) YAYIAddMemberType curAddMenberType;
@property (nonatomic, strong) NSMutableArray *curChangedPatientArray;

@end

@implementation YAYIEditTagGroupViewController


- (NSMutableArray *)patientArray
{
    if (nil == _patientArray) {
        _patientArray = [NSMutableArray array];
    }
    return _patientArray;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    self.view.backgroundColor = [UIColor colorWithWhite:0.965 alpha:1];
    self.title = @"标签";
    
    [self setupNav];
    [self setupHeadView];
    [self setupCollectionView];
    
    
//    if (self.tagID) {
//        [self createDataSource];
//        self.groupNameTf.text = self.tagName;
//    }
}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    if (self.tagID && YAYIAddMemberTypeNew != self.addMenberType) {
        [self createDataSource];
        self.groupNameTf.text = self.tagName;
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.groupNameTf resignFirstResponder];
}


- (void)setupNav
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    //    [button setImage:[UIImage imageNamed:@"back_button"] forState:UIControlStateNormal];
    [button setTitle:@"保存" forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    
    button.frame = (CGRect){{0, 0}, CGSizeMake(70, 30)};
    
    // 让按钮内部的所有内容左对齐
    button.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [button addTarget:self action:@selector(saveAction:) forControlEvents:UIControlEventTouchUpInside];
    
    // 修改导航栏左边的item
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:button];
}


- (void)setupHeadView
{
    UIView *headView = [[UIView alloc] init];
    headView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:headView];
    self.headView = headView;
    [headView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(64);
        make.left.equalTo(self.view);
        make.height.equalTo(@50);
        make.width.equalTo(@(SCREEN_width));
    }];
    
    UILabel *titleLbl = [[UILabel alloc] init];
    titleLbl.text = @"分组名称";
    titleLbl.font = [UIFont systemFontOfSize:16];
    titleLbl.textColor = YAYIColor(89, 88, 88);
    [headView addSubview:titleLbl];
    [titleLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(@20);
        make.centerY.equalTo(headView);
    }];
    
    UITextField *tf = [[UITextField alloc] init];
    tf.placeholder = @"输入组名";
    tf.font = [UIFont systemFontOfSize:16];
    tf.textColor = YAYIColor(160, 160, 160);
    tf.textAlignment = NSTextAlignmentRight;
    [headView addSubview:tf];
    self.groupNameTf = tf;
    [tf mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(titleLbl.mas_right).offset(20);
        make.right.equalTo(headView).offset(-20);
        make.height.equalTo(@20);
        make.centerY.equalTo(headView);
    }];
    
    // 线
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = YAYIColor(0xe0, 0xe0, 0xe0);
    [headView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@0.5);
        make.width.equalTo(@(SCREEN_width));
        make.left.equalTo(@0);
        make.bottom.equalTo(headView);
    }];
    
}


- (void)setupCollectionView
{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    //设置对齐方式
//    [flowLayout setScrollDirection:UICollectionViewScrollDirectionHorizontal];
    //cell间距
    flowLayout.minimumInteritemSpacing = 20.0f;
    //cell行距
    flowLayout.minimumLineSpacing = 20.0f;
    
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 70 + 64, SCREEN_width, SCREEN_height - 70 - 64) collectionViewLayout:flowLayout];
//    collectionView.collectionViewLayout = flowLayout;
    
    collectionView.backgroundColor = [UIColor whiteColor];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    
    //注册Cell，必须要有
    [collectionView registerClass:[YAYIEditTagGroupCollectionCell class] forCellWithReuseIdentifier:@"GradientCell"];
    
    [self.view addSubview:collectionView];
    self.collectionView = collectionView;
    
//    collectionView.frame = CGRectMake(0, 0, SCREEN_width, 200);
    
//    [collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.right.equalTo(self.view);
//        make.top.equalTo(self.headView.mas_bottom).offset(20);
//        make.height.equalTo(@200);
//    }];
    
    // 线
    UIView *lineView1 = [[UIView alloc] init];
    lineView1.backgroundColor = YAYIColor(0xe0, 0xe0, 0xe0);
    [self.view addSubview:lineView1];
    [lineView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@0.5);
        make.width.equalTo(@(SCREEN_width));
        make.left.equalTo(@0);
        make.top.equalTo(collectionView);
    }];
    
    UIView *lineView2 = [[UIView alloc] init];
    lineView2.backgroundColor = YAYIColor(0xe0, 0xe0, 0xe0);
    [collectionView addSubview:lineView2];
    self.bottomLineView = lineView2;
    [lineView2 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@0.5);
        make.width.equalTo(@(SCREEN_width));
        make.left.equalTo(@0);
        make.top.equalTo(collectionView).offset(100);
    }];
}

- (void)setLineViewY
{
    int columnCount = 4;
    if (SCREEN_width > 320) {
        columnCount = 5;
    }else{
        columnCount = 4;
    }
    
    int rowCount = (int)(self.patientArray.count + 2) / columnCount;
    if ((self.patientArray.count + 2) % columnCount) {
        rowCount++;
    }
    
//    self.bottomLineView.mj_y = (60 + 20) * rowCount + 20;
    [self.bottomLineView mas_updateConstraints:^(MASConstraintMaker *make) {

        make.top.equalTo(self.collectionView).offset((60 + 20) * rowCount + 20);
    }];
}

#pragma mark - 获取数据

/**
 *  字典转模型
 */
- (void)setModelData
{
    for (NSDictionary *dict in self.serverDataArr)
    {
        YAYIMyPatientItem *model = [[YAYIMyPatientItem alloc] init];
        [model setValuesForKeysWithDictionary:dict];
        [self.patientArray addObject:model];
    }
    
    [self setLineViewY];
}


- (void)createDataSource
{
    // 显示hud
    [SVProgressHUD show];
    
    [self.patientArray removeAllObjects];
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"tagid"] = self.tagID;
    
    [YAYINetWorking getWithURL:patienTagClient_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error) {
        if (error == nil) {
            YAYILog(@"返回：%@", dict);
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
            }else{
                NSArray *data = dict[@"data"];
                
                for (NSDictionary *obj in data) {
                    YAYIMyPatientItem *item = [YAYIMyPatientItem new];
                    [item setValuesForKeysWithDictionary:obj];
                    
                    [self.patientArray addObject:item];
                    YAYILog(@"item.clientname:%@", item.clientname);
                }
                
                [self setLineViewY];
                [self.collectionView reloadData];
            }

        }else{
            
            YAYILog(@"erro:%@", error);
        }
        
        // 取消显示hud
        [SVProgressHUD dismiss];
    }];
    
}




#pragma mark - 点击事件方法
- (void)goBack
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)saveAction:(UIButton *)sender
{
    YAYILog(@"点击了保存");
    
    if (YAYIAddMemberTypeNew == self.addMenberType) { // 新建标签
        
        [self newTag];
    }else{
    
        NSMutableString *patientIDs = [NSMutableString string];
        
        for (int i = 0; i < self.patientArray.count; i++) {
            YAYIMyPatientItem *model = self.patientArray[i];
            [patientIDs appendFormat:@"%ld", model.dcid];
            if (i != self.patientArray.count - 1) {
                [patientIDs appendString:@","];
            }
        }
        
        NSMutableDictionary *param = [NSMutableDictionary dictionary];
        param[@"tagid"] = self.tagID;
        param[@"dcids"] = patientIDs;
        
        YAYILog(@"parm:%@", param);
        
        [YAYINetWorking postJsonSerilizeWithURL:patienAddTagGroup_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error,NSDictionary *responseError) {
            if (error == nil) {
                YAYILog(@"保存标签：%@", dict);
                
                if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
                    [SVProgressHUD showWithStatus:@"保存失败"];
                    
                }else{
                    [SVProgressHUD showSuccessWithStatus:@"保存成功"];
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self goBack];
                        // 执行代理刷新上级控制器
                        if ([self.delegate respondsToSelector:@selector(editTagGroupHaveAddTag)]) {
                            [self.delegate editTagGroupHaveAddTag];
                        }
                    });
                }
            }else{
                NSString *message = responseError[@"message"];
                [SVProgressHUD showWithStatus:message];
            }
        }];
    }  
}

/**
 *  新建标签
 */
- (void)newTag
{
    if (self.groupNameTf.text.length == 0) {
        [SVProgressHUD showErrorWithStatus:@"请输入组名"];
        return;
    }
    
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"name"] = self.groupNameTf.text;
    
    if (self.patientArray.count > 0) {
        
        NSMutableString *patientIDs = [NSMutableString string];
        
        for (int i = 0; i < self.patientArray.count; i++) {
            YAYIMyPatientItem *model = self.patientArray[i];
            [patientIDs appendFormat:@"%ld", model.dcid];
            if (i != self.patientArray.count - 1) {
                [patientIDs appendString:@","];
            }
        }
        param[@"dcids"] = patientIDs;
    }
    
    YAYILog(@"parm:%@", param);
    
    [YAYINetWorking postJsonSerilizeWithURL:patienAddTag_url param:param finish:^(NSData *data, NSDictionary *dict, NSError *error,NSDictionary *responseError) {
        if (error == nil) {
            YAYILog(@"保存标签：%@", dict);
            
            if (dict == nil || [dict isKindOfClass:[NSNull class]] || ![dict[@"status"] isEqualToString:@"success"]) {
                [SVProgressHUD showWithStatus:@"保存失败"];
                
            }else{
                [SVProgressHUD showSuccessWithStatus:@"保存成功"];
                
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self goBack];
                    // 执行代理刷新上级控制器
//                    if ([self.delegate respondsToSelector:@selector(editTagGroupHaveAddTag)]) {
//                        [self.delegate editTagGroupHaveAddTag];
//                    }
                });
            }
        }else{
            NSString *message = responseError[@"message"];
            [SVProgressHUD showWithStatus:message];
        }
    }];
}



#pragma mark - 代理方法
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (self.patientArray.count == 0) {
        return 1;
    }
    return self.patientArray.count + 2;
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString * CellIdentifier = @"GradientCell";
    YAYIEditTagGroupCollectionCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:CellIdentifier forIndexPath:indexPath];
    
    if (indexPath.row == self.patientArray.count) {
        cell.iconView.image = [UIImage imageNamed:@"addPatient"];
        cell.nameLbl.text = nil;
    }else if (indexPath.row == self.patientArray.count + 1) {
        cell.iconView.image = [UIImage imageNamed:@"subPatient"];
        cell.nameLbl.text = nil;
    
    }else{
//        cell.iconView.image = [UIImage imageNamed:@"2"];
        YAYIMyPatientItem *model = self.patientArray[indexPath.row];
        cell.item = model;
    }
    
    
    
    return cell;
}


//定义每个UICollectionViewCell 的大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return CGSizeMake(50, 60);
}
//定义每个Section 的 margin
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(20, 20, 20, 20);//分别为上、左、下、右
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    YAYILog(@"row:%ld section:%ld", indexPath.row, indexPath.section);
    
    if (indexPath.row == self.patientArray.count) {
        YAYILog(@"添加组员");
        
        self.curAddMenberType = YAYIAddMemberTypeAdd;
        YAYIAddMemberViewController *addMemberVc = [[YAYIAddMemberViewController alloc] init];
        addMemberVc.addMemberType = self.addMenberType;
        addMemberVc.delegate = self;
        addMemberVc.tagID = self.tagID;
        [self.navigationController pushViewController:addMemberVc animated:YES];
        
    }else if (indexPath.row == self.patientArray.count + 1){
        
        self.curAddMenberType = YAYIAddMemberTypeDel;
        NSMutableArray *modelArray = [NSMutableArray array];
        for (YAYIMyPatientItem *model in self.patientArray) {
            YAYIMyPatientItem *newModel = [model copy];
            [modelArray addObject:newModel];
        }
        
        YAYIAddMemberViewController *addMemberVc = [[YAYIAddMemberViewController alloc] init];
        addMemberVc.addMemberType = YAYIAddMemberTypeDel;
//        BOOL isNew = self.addMenberType == YAYIAddMemberTypeNew;
        addMemberVc.isNew = self.addMenberType == YAYIAddMemberTypeNew;
        
        addMemberVc.curPatientArray = [modelArray mutableCopy];
        addMemberVc.delegate = self;
        addMemberVc.tagID = self.tagID;
        [self.navigationController pushViewController:addMemberVc animated:YES];
    }
    
    
}

#pragma mark YAYIAddMemberViewControllerDelegate
- (void)addMemberBy:(NSArray *)patienArry
{
    if (self.addMenberType == YAYIAddMemberTypeNew) { // 新建
        
        self.patientArray = [patienArry mutableCopy];
        [self.collectionView reloadData];
        [self setLineViewY];
        
    }
    
}

- (void)addMemberBy:(NSArray *)selectedArray notSelectedArray:(NSArray *)notSelectedArray
{
//    if (self.curAddMenberType == YAYIAddMemberTypeNew) { // 新建
//        [self.patientArray addObjectsFromArray:selectedArray];
//    }else if (self.curAddMenberType == YAYIAddMemberTypeDel){  // 删除
//        self.patientArray = [NSMutableArray arrayWithArray:notSelectedArray];
//    }else{  // 添加
//        [self.patientArray addObjectsFromArray:selectedArray];
//    }
    if (YAYIAddMemberTypeNew == self.addMenberType) {
        self.patientArray = [NSMutableArray arrayWithArray:notSelectedArray];
    }
    
    [self.collectionView reloadData];
    [self setLineViewY];
}

@end
